package com.tb.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 何龙
 */
public class QiniuUploadImageUtil {

    //accessKey
    private static String accessKey = "DtBv2HVmxCSzDivcdIQ6empwk5p3PXY3po043JLX";
    //secretKey
    private static String secretKey ="RG0mCV1MOAQL5QgBxXWR2GSvbWfRxUWTTlPWPjr7";
    //储存空间名
    private static String bucket ="hll-jingdong";
    //外链URL前缀
    private static String fronturl = "http://pky36u4fr.bkt.clouddn.com/";


    /**
     * 图片上传

     * @param file  图片路径
     * @return  链接
     * @throws QiniuException
     */
    public static  String  fileUpload(String file)throws QiniuException {
        Auth auth = Auth.create(accessKey,secretKey);
        String upToken = auth.uploadToken(bucket);
        Configuration cfg = new Configuration(Zone.autoZone());
        UploadManager uploadManager = new UploadManager(cfg);
        String key  = null;
        try {
            Response response = uploadManager.put(file, key, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
            return fronturl+putRet.key;
        }catch (QiniuException ex){
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                // ignore
            }
        }
        return null;
    }

    /**
     * 判断文件是否合法
     * @param img 文件绝对路径
     * @return 状态码 0合法 1文件类型错误 2文件路径不合法
     */
    public static int imgType(String img){
        String regEx = "\\.[^.\\\\/:*?\"<>|\\r\\n]+$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(img);

        if (!m.find()) {
            System.out.println("文件路径格式错误!");
            return 2;
        }
        String group = m.group();
        if (".BMP".equalsIgnoreCase(group)){
            return 0;
        }else if (".JPG".equalsIgnoreCase(group)){
            return 0;
        }else if (".JPEG".equalsIgnoreCase(group)){
            return 0;
        }else if (".PNG".equalsIgnoreCase(group)){
            return 0;
        }else if (".GIF".equalsIgnoreCase(group)){
            return 0;
        }else {
            return 1;
        }
    }
}